#include "kernel/types.h"
#include "user/user.h"

#define RD 0
#define WR 1

void get_prime(int lp[2]){
    int num;
    int rp[2];
    int pid;

    close(lp[WR]);
    
    if(!read(lp[RD], &num, sizeof(int))){
        close(lp[RD]);
        exit(0);
    }
    printf("prime %d\n", num);   
    pipe(rp);
    pid = fork();
    if (pid==0){    //child progress
        get_prime(rp);
        
    } else if (pid>0){  //parent progress
        int temp;
        while (read(lp[RD], &temp, sizeof(int))) {
            if(temp % num){
                write(rp[WR], &temp, sizeof(int));
            }
        }
        close(lp[RD]);
        close(lp[WR]);
        close(rp[RD]);
        wait(0);
        printf("stop");
    } else {
        fprintf(2, "ERROR: fork()");
        exit(pid);
    }
    exit(0);
}


int main(int argc, char *argv[]){
    int p[2];
    pipe(p);
    for (int i=2; i<=35; i++) {
        write(p[WR], &i, sizeof(int));
    }
    get_prime(p);
    exit(0);
}